#!/usr/bin/env python
"""Convert texstudio cwl files to VimTeX format"""
import os
import re


with open('tools/symbols') as f:
    SYMBOLS = dict([line.strip().split(' ') for line in f.readlines()])


with open('default') as f:
    DEFAULT = [line.strip().split(' ')[0] for line in f.readlines()]


RE_CMD = re.compile(r'\w+\*?')
RE_ENV = re.compile(r'\\begin\{(\w+\*?)\}')


files = [['texstudio-cwls/' + f, os.path.splitext(f)[0]]
         for f in os.listdir('texstudio-cwls')]
for infile, outfile in files:
    with open(infile, encoding='latin1') as f:
        lines = f.readlines()

    includes = [line for line in lines if line[0:4] == '#inc']
    commands = sorted(set([RE_CMD.search(line).group(0)
                           for line in lines
                           if line[0] == '\\']),
                      key=lambda l: (l.lower(), l.swapcase()))
    commands = [cmd for cmd in commands if cmd not in DEFAULT]
    commands = [cmd for cmd in commands if len(cmd) > 3]
    commands = [[cmd, SYMBOLS.get(cmd, '')] for cmd in commands]
    commands = [' '.join(cmd).strip() + '\n' for cmd in commands]

    environs = sorted(set([res.group(1)
                           for res in [RE_ENV.search(line)
                               for line in lines
                               if line[0] == '\\']
                           if res is not None]),
                      key=lambda l: (l.lower(), l.swapcase()))
    environs = [r'\begin{'+env+'}' for env in environs]
    environs = [env for env in environs if env not in DEFAULT]
    environs = [env+'\n' for env in environs]

    with open(outfile, 'w') as f:
        for line in includes + commands + environs:
            f.write(line)
